package com.moorror.codegenvel.view.window.codegen.tree;

import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.Project;
import com.moorror.codegenvel.common.tree.MTTreeCell;
import com.moorror.codegenvel.common.tree.TreePanelMark;
import com.moorror.codegenvel.common.tree.actions.DeleteRightContentSqliteAction;
import com.moorror.codegenvel.common.tree.actions.SaveRightContentSqliteAllAction;
import com.moorror.codegenvel.common.tree.actions.gencode.GenCodeVelocityAction;
import com.moorror.codegenvel.db.sqlite.dao.BaseDAO;
import com.moorror.codegenvel.db.sqlite.dao.impl.CodeGenSceneTemplateDaoImpl;
import com.moorror.codegenvel.db.sqlite.dao.impl.CodeGenTemplateDaoImpl;
import com.moorror.codegenvel.db.sqlite.entity.AbEntity;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenSceneTemplate;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenTemplate;
import com.moorror.codegenvel.domain.bean.savefile.GenerateOptions;
import com.moorror.codegenvel.domain.bean.savefile.SaveFileDesc;
import com.moorror.codegenvel.utils.GuiUtils;
import com.moorror.codegenvel.utils.JacksonUtils;
import com.moorror.codegenvel.utils.VelocityUtils;
import com.moorror.codegenvel.view.component.CodeGenByVelocityComponent;
import com.moorror.codegenvel.view.component.TabContentRightShow;
import com.moorror.codegenvel.view.window.codegen.view.CodeGenTemplatePanel;
import lombok.Getter;
import org.apache.commons.lang3.tuple.Pair;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Map;

/**
 * @Author jiyanghuang
 * @Date 2024/4/11 23:14
 */
public class MTTreeCellCodeGenData implements MTTreeCell {

    private Project project;

    @Getter
    private CodeGenTemplatePanel codeGenTemplatePanel;

    @Getter
    private CodeGenTemplate codeGenTemplate;


    /**
     *
     * @param project
     * @param codeGenTemplate
     */
    public MTTreeCellCodeGenData(Project project, CodeGenTemplate codeGenTemplate) {
        this.project = project;
        this.codeGenTemplate = codeGenTemplate;
    }

    @Override
    public String cellShow() {
        return this.codeGenTemplate.getName();
    }

    @Override
    public Icon iconSelected() {
        return GuiUtils.CODE_GEN_VM;
    }

    @Override
    public Icon iconUnselected() {
        return GuiUtils.CODE_GEN_VM;
    }

    @Override
    public void treeSelectionListener(JTree tree, DefaultMutableTreeNode mutableTreeNode, TreePanelMark treePanelMark) {
        try {
            if (null == codeGenTemplatePanel) {
                codeGenTemplatePanel = new CodeGenTemplatePanel(project, codeGenTemplate);
            }
            TabContentRightShow tabContentRightShow = CodeGenByVelocityComponent.getInstance(project).findInstance(TabContentRightShow.class);
            tabContentRightShow.updatePanel(codeGenTemplatePanel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public ActionGroup rightClickActionGroup(JTree tree, DefaultMutableTreeNode mutableTreeNode, DefaultActionGroup defaultActionGroup, TreePanelMark treePanelMark) {
        defaultActionGroup.add(new GenCodeVelocityAction(treePanelMark, "Gen code velocity", "Gen code velocity"));
        defaultActionGroup.add(new SaveRightContentSqliteAllAction(treePanelMark, "saveTemplateToSqlite", "save template to sqlite"));
        defaultActionGroup.add(new DeleteRightContentSqliteAction(treePanelMark, "deleteTemplateFromSqlite", "delete tempalte from sqlite"));
        return defaultActionGroup;
    }

    @Override
    public void genCodeVelocity(TreePanelMark treePanelMark, DefaultMutableTreeNode mutableTreeNode) {
        if (null == mutableTreeNode.getParent()) {
            return;
        }
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) mutableTreeNode.getParent();
        MTTreeCell parentCell = (MTTreeCell) parent.getUserObject();
        if(!(parentCell instanceof MTTreeCellCodeGenScene)){
            return;
        }
        /**
         * 生成前更新一下数据
         */
        if(null != codeGenTemplatePanel){
            codeGenTemplatePanel.fetchValue();
        }

        /**
         * 跳过当前生成
         */
        if(codeGenTemplate.isSkipGenCode()){
            return;
        }
        MTTreeCellCodeGenScene codeGenScene = (MTTreeCellCodeGenScene)parentCell;
        // 构建参数
        Map<String, Object> param = VelocityUtils.fetchDefaultParam();
        param.putAll(JacksonUtils.toMapDefault(codeGenScene.velocityContext()));
        SaveFileDesc saveFileDesc = new SaveFileDesc();
        GenerateOptions generateOptions = new GenerateOptions();
        generateOptions.setTitleSure(false);
        generateOptions.setTitleRefuse(false);
        saveFileDesc.setGenerateOptions(generateOptions);
        saveFileDesc.setProject(project);
        saveFileDesc.setSkipGenCode(codeGenTemplate.isSkipGenCode());
        saveFileDesc.setCoverPrompt(codeGenTemplate.isCoverPrompt());
        VelocityUtils.generate(saveFileDesc, param, codeGenTemplate);
//        Set<String> extractVariables = VelocityUtils.extractVariables(codeGenTemplate.getContent());
//        saveFileDesc.setContent(extractVariables.toString());
        if(null != codeGenTemplatePanel){
            codeGenTemplatePanel.replaceResult(saveFileDesc);
        }
    }

    @Override
    public void saveRightContentSqlite(TreePanelMark treePanelMark, DefaultMutableTreeNode mutableTreeNode) {
        try {
            /**
             * 界面没有打开，没有填充数据
             */
            if (null == codeGenTemplatePanel) {
                return;
            }
            /**
             * 右边得有统一的 fetchValue 然后保存
             */
            codeGenTemplatePanel.fetchValue();

            Object obj = parentUserObject(mutableTreeNode);
            if (null == obj || !(obj instanceof MTTreeCellCodeGenScene)) {
                return;
            }
            MTTreeCellCodeGenScene codeGenScene = (MTTreeCellCodeGenScene) obj;

            CodeGenSceneTemplate codeGenSceneTemplate = AbEntity.of(CodeGenSceneTemplate.class);
            String reJson = codeGenTemplate.fetchJsonValueNToMN();
            codeGenSceneTemplate.setJsonSceneTemplate(reJson);
            codeGenSceneTemplate.setScene(codeGenScene.getCodeGenScene().getName());
            codeGenSceneTemplate.setTemplate(codeGenTemplate.getName());

            /**
             * 更新表
             */
            BaseDAO.update(CodeGenTemplateDaoImpl.getInstance(), codeGenTemplate);
            BaseDAO.update(CodeGenSceneTemplateDaoImpl.getInstance(), codeGenSceneTemplate);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void deleteRightContentFromSqlite(DefaultMutableTreeNode mutableTreeNode, TreePanelMark treePanelMark) {
        try{
            /**
             * 界面没有打开，没有填充数据
             */
            if (null == codeGenTemplatePanel) {
                return;
            }

            Object obj = parentUserObject(mutableTreeNode);
            if (null == obj || !(obj instanceof MTTreeCellCodeGenScene)) {
                return;
            }
            MTTreeCellCodeGenScene codeGenScene = (MTTreeCellCodeGenScene) obj;
            CodeGenSceneTemplate codeGenSceneTemplate = AbEntity.of(CodeGenSceneTemplate.class);
            codeGenSceneTemplate.setScene(codeGenScene.getCodeGenScene().getName());
            codeGenSceneTemplate.setTemplate(codeGenTemplate.getName());

            /**
             * 删除数据
             */
            BaseDAO.delete(Lists.newArrayList(Pair.of(CodeGenTemplateDaoImpl.getInstance(), codeGenTemplate), Pair.of(CodeGenSceneTemplateDaoImpl.getInstance(), codeGenSceneTemplate)));
            this.removeCurrent(treePanelMark.jTree(), mutableTreeNode);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

}
